<?php


namespace App\Repositories\Settings;


use App\Models\BaseModel;
use App\Models\Settings\Code;
use App\Models\Settings\CodeValue;
use App\Repositories\BaseRepository;
use App\Utils\Output;
use App\Utils\QueryHelper;

class CodeRepository extends BaseRepository
{
    function adminPager($params)
    {
        extract($params);
        $query = Code::query();
        if (!empty($keyword)) {
            QueryHelper::like($query, 'settings__codes.name|settings__codes.code', $keyword);
        }
        if (!empty($module)) {
            $query->where('module', '=', $module);
        }
        $totalQuery = clone $query;
        $total = $totalQuery->count();
        $query->select(
            'settings__codes.id',
            'settings__codes.name',
            'settings__codes.module',
            'settings__codes.module as module_text',
            'settings__codes.code',
            'settings__codes.desc',
            'settings__codes.created_at',
            'settings__codes.updated_at'
        );
        $lis = $this->setParams($query, $params);
        return Output::pager($lis, $total);
    }

    protected function deleteAfter(array $ids)
    {
        $codes = Code::withTrashed()->whereIn('id', $ids)->pluck('code');
        CodeValue::query()->whereIn('code', $codes)->delete();
    }

    function getMap($code)
    {
        if (isset(self::$codeMap[$code])) {
            return self::$codeMap[$code];
        }
        $lis = CodeValue::query()->where('code', '=', $code)->orderByDesc('weight')->select('name', 'value')->get();
        $map = array();
        foreach ($lis as $li) {
            $map[$li->value] = $li->name;
        }
        self::$codeMap[$code] = $map;
        return $map;
    }

    function getModel(): BaseModel
    {
        return new Code();
    }

    static $codeMap = [];
}
